/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.shop.web.controllers;

import com.google.gson.Gson;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.shop.domain.SoldItemDescription;
import org.shop.domain.Store;
import org.shop.service.InventoryService;
import org.shop.utils.InstanceUtils;
import org.shop.web.utils.RootController;

/**
 *
 * @author vinod
 */
public class KeyController extends RootController {

    private static final Logger log = Logger.getLogger(KeyController.class);
    private Gson gson = new Gson();

    @Override
    protected void doWork(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        InstanceUtils utils = new InstanceUtils();
        PrintWriter out = response.getWriter();
        InventoryService service = utils.getService();
        String param = request.getParameter("info").trim();
        log.debug(param);
        if (param.equals("names")) {
            String content = request.getParameter("criteria").trim();
            List list = service.getCustomerByKey(content);
            if (list.size() > 0) {
                log.info(list);
                out.println(new Gson().toJson(list));
            }
        }
        if (param.equals("itemId")) {
            String content = request.getParameter("criteria").trim();
            Store store = service.getItemsByKey(content);

            if (store == null) {
                out.println("Item Id Avaliabled...!");
            } else {
                log.debug(store.toString());
                log.debug("GSON Object" + gson.toJson(store));
                out.println(gson.toJson(store));
            }

        }
        if (param.equals("itemDescription")) {
            String custName = request.getParameter("custName").trim();
            Date descDate = getDate(request.getParameter("date").trim());
            long mobile = Long.valueOf(request.getParameter("mobile").trim());
            List<SoldItemDescription> descList = service.getSoldItemDetails(custName, mobile, descDate);
            out.println(gson.toJson(descList));
        }
    }

    private Date getDate(String date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date resultDate = null;
        try {
            resultDate = format.parse(date);
        } catch (ParseException ex) {
            log.warn("Parsing Exception" + ex.getMessage());
        }
        return resultDate;
    }
}
